package com.yc.cinema.aop;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLIBProxy {

    // CGLIB 基于继承
    public static <T> T proxy(T t ){
        Enhancer enhancer = new Enhancer();
        // 设值父类
        enhancer.setSuperclass(t.getClass());
        // 设值回调 => 方法拦截
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                final Object ret = methodProxy.invoke(t, objects);
                System.out.println("交通方便, 购物便利");
                return ret;
            }
        });
        // 创建对象
        final Object o = enhancer.create();
        return (T) o;
    }
}
